package com.haiertvbic.tvnow;

import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.tvnow.baseactivity.BaseActivity;
import com.haiertvbic.tvnow.callback.JsonService;
import com.haiertvbic.tvnow.callback.MoreTv;
import com.haiertvbic.tvnow.db.DbAdapter;
import com.haiertvbic.tvnow.model.OTTInfo;
import com.haiertvbic.tvnow.model.ProgramItem;
import com.haiertvbic.tvnow.model.ProgramOTT;
import com.haiertvbic.tvnow.model.ThridProgram;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.network.NetUtil;
import com.haiertvbic.tvnow.pop.ProgramJSPop;
import com.haiertvbic.tvnow.testblock.Function;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.Util;

public class OTTInfoActivity extends BaseActivity {
	private Activity context = OTTInfoActivity.this;
	private String TAG = "OTTInfoActivity";
	private String programName;
	private String startActivity;
	private String programType;
	private String js;

	private ExpandableListView expandListview;
	private TextView loading;
	private ProgressBar loadingBar;

	// 取节目
	private Thread programThread;
	private Handler mhandler;
	private boolean isOutTme;
	ArrayList<OTTInfo> ottList;

	private OttGroupAdapter adapter;
	HashMap<String, SoftReference<Bitmap>> logoCache = new HashMap<String, SoftReference<Bitmap>>();

	private View childView;

	@Override
	protected void onResume() {
		Util.initToOtherApk(context);
		super.onResume();
	}

	@Override
	public void findView() {
		getQueryData();
		setContentView(R.layout.activity4_expandable_list);
		TextView programNameTV = (TextView) findViewById(R.id.pro_name);
		programNameTV.setText(programName);
		TextView screenPoint = (TextView) findViewById(R.id.screen_point);
		String ottScreen = getString(R.string.ott_infor);
		screenPoint.setText(ottScreen);
		ImageView screenGuide = (ImageView) findViewById(R.id.screen_point_iv);
		screenGuide.setImageResource(R.drawable.ott_screen_guide_4);

		loading = (TextView) findViewById(R.id.loading_tv);
		loadingBar = (ProgressBar) findViewById(R.id.bar_on_cha);
		expandListview = (ExpandableListView) findViewById(R.id.expandable_lv);
		expandListview.setGroupIndicator(null);
		expandListview.setDivider(null);
		expandListview.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				childView = arg1;
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		expandListview.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				OTTInfo resource = ottList.get(groupPosition);
				ThridProgram thridProgram = resource.getPrograms().get(
						childPosition);
				callApk(thridProgram, resource, context);
				return false;
			}
		});
		expandListview.setOnGroupExpandListener(new OnGroupExpandListener() {

			@Override
			public void onGroupExpand(int groupPosition) {
				for (int i = 0; i < adapter.getGroupCount(); i++) {
					// ensure only one expanded Group exists at every time
					if (groupPosition != i
							&& expandListview.isGroupExpanded(groupPosition)) {
						expandListview.collapseGroup(i);
					}
				}
			}
		});
		expandListview.setOnGroupClickListener(new OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				OTTInfo resource = ottList.get(groupPosition);
				expandListview.setSelection(groupPosition);
				if (resource.getIs().equals("web")
						&& resource.getWeb().equals("1")) {
					// 开启浏览器
					String programUrl = resource.getProgramUrl();
					Intent intent = new Intent();
					intent.setClass(context, OttWebViewActivity.class);
					intent.putExtra("OTT_URL", programUrl);
					context.startActivity(intent);
					return true;
				} else {
					return false;
				}
			}
		});
	}

	@Override
	public void setDataSetup() {
		loadingBar.setVisibility(View.VISIBLE);
		loading.setVisibility(View.GONE);

		if (programThread != null) {
			programThread = null;
		}
		programThread = new Thread(new Runnable() {
			private ProgramOTT programOTT;

			@Override
			public void run() {
				if (NetUtil.getNetworkInfo(context)) {
					encodingData();
					try {
						programOTT = EPGWeb.getOttList(context, programName,
								js, programType);
						SLog.d(TAG, "programType=" + programType + "PRO_NAME="
								+ programName);
						ottList = programOTT != null ? programOTT
								.getHaierOttList() : null;
						if (ottList != null && ottList.size() > 0) {
							mhandler.sendEmptyMessage(EPGWeb.DATA_SUC);
						} else {
							mhandler.sendEmptyMessage(EPGWeb.SERVER_NO_DATA);
						}
					} catch (ClientProtocolException e) {
						mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
					} catch (IOException e) {
						mhandler.sendEmptyMessage(EPGWeb.SERVER_REQUEST_OUTIME);
					}

					// setTestData();
				} else {
					mhandler.sendEmptyMessage(EPGWeb.NO_NETWORK);
				}
			}

			private void encodingData() {
				DbAdapter dbdata = new DbAdapter();
				dbdata.getInstance(context);
				ArrayList<ProgramItem> fatherItems = dbdata.findFathertItem();
				String[] types = programType.split(",");
				for (int typeCount = 0; typeCount < types.length; typeCount++) {
					for (int j = 0; j < fatherItems.size(); j++) {
						String itemType = fatherItems.get(j).getNode();
						if (types[typeCount].equals(itemType)) {
							programType = types[typeCount];
							break;
						}
					}
				}
			}

		});
		programThread.start();
		if (mhandler != null) {
			return;
		}
		mhandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				loadingBar.setVisibility(View.GONE);
				switch (msg.what) {
				case EPGWeb.DATA_SUC:
					adapter = new OttGroupAdapter(ottList);
					expandListview.setAdapter(adapter);
					for (int i = 0; i < ottList.size()
							&& ottList.get(i) != null; i++) {
						ArrayList<ThridProgram> programs = ottList.get(i)
								.getPrograms();
						String more = ottList.get(i).getMore();
						if (more != null && more.trim().length() > 0
								&& !more.equals("N") && programs != null
								&& programs.size() > 0) {
							ThridProgram program = new ThridProgram();
							program.setName("more...");
							programs.add(program);
						}
					}
					expandListview.setVisibility(View.VISIBLE);
					loading.setVisibility(View.GONE);
					expandListview.requestFocus();
					expandListview.setFocusable(true);
					break;
				case EPGWeb.SERVER_NO_DATA:
					expandListview.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.server_no_data);
					break;
				case EPGWeb.SERVER_REQUEST_OUTIME:
					expandListview.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					String again = getString(R.string.server_request_outime);
					loading.setText(again);
					isOutTme = true;
					break;
				case EPGWeb.NO_NETWORK:
					expandListview.setVisibility(View.GONE);
					loading.setVisibility(View.VISIBLE);
					loading.setText(R.string.NOnetwork);
					break;

				default:
					break;
				}
			}
		};
	}

	public void callApk(ThridProgram thridProgram, OTTInfo resource,
			final Activity context) {
		String programUrl = thridProgram.getLink();
		if (thridProgram.getName().equals("more...")) {
			// 调pop
			String moreUrl = resource.getMore().trim();
			if (moreUrl != null && moreUrl.length() > 0) {
				new ProgramJSPop(context, childView, resource).showPop();
			}
		} else if (programUrl != null && programUrl.trim().length() > 0) {
			Util.startBrower(programUrl, context);
		} else {
			String apkName = resource.getApkName();
			boolean isInstall = false;
			if (apkName != null && apkName.trim().length() > 0) {
				isInstall = Util.checkApk(context, apkName);
			}
			if (isInstall) {
				final String pid = thridProgram.getPid();
				if (apkName.equals("com.voole.epg")) {
					PackageManager pm = getPackageManager();
					Intent intent = pm
							.getLaunchIntentForPackage("com.voole.epg");
					intent.putExtra("TARGET", "VOOLE_DETAIL");
					intent.putExtra("VOOLE_DETAIL_PARAM", pid);
					Util.toOtherApk(context);
					startActivity(intent);
				} else if (apkName.equals("com.moretv.tvapp")) {
					JsonService.paserMoreTv(new MoreTv() {
						@Override
						public void returnData(String userID, String token) {
							Intent intent = new Intent();
							intent.setAction("moretv.service.action");
							intent.putExtra("userid", userID);
							intent.putExtra("Token", token);
							intent.putExtra("Data", pid);
							intent.putExtra("launcher", 1);
							intent.putExtra("ReturnMode", 0);
							Util.toOtherApk(context);
							startActivity(intent);
						}
					});

				}
			} else {
				// 没装开浏览器到下载页
				try {
					Util.startBrower(resource.getPath(), context);
				} catch (Exception e) {
					Toast.makeText(context, "下载路径不正确", 1).show();
				}

			}

		}
	}

	class LogoAsyncTask extends AsyncTask<String, Void, Void> {

		private Bitmap posterBit;

		@Override
		protected Void doInBackground(String... params) {
			String posterUrl = params[0];
			posterBit = null;
			posterBit = EPGWeb.getBitmapFromURL(context, posterUrl);
			logoCache.put(posterUrl, new SoftReference<Bitmap>(posterBit));
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (posterBit != null && adapter != null) {
				adapter.notifyDataSetChanged();
			}
			super.onPostExecute(result);
		}
	}

	class OttGroupAdapter extends BaseExpandableListAdapter {
		private ArrayList<OTTInfo> resGroup;
		private LogoAsyncTask logoAsync;
		private ArrayList<ThridProgram> programNetRes;

		public OttGroupAdapter(ArrayList<OTTInfo> ottList) {
			this.resGroup = ottList;
		}

		@Override
		public Object getChild(int arg0, int arg1) {
			return null;
		}

		@Override
		public long getChildId(int arg0, int arg1) {
			return 0;
		}

		class ChildHolder {
			TextView resProgram;
			ImageView directro;
		}

		@Override
		public View getChildView(int groupPosition, int arg1, boolean arg2,
				View convertView, ViewGroup arg4) {
			ChildHolder holder = new ChildHolder();
			if (convertView == null) {
				convertView = View.inflate(context, R.layout.layout_ott_child,
						null);
				holder.resProgram = (TextView) convertView
						.findViewById(R.id.net_resrouce_program);
				holder.directro = (ImageView) convertView
						.findViewById(R.id.directro);
				convertView.setTag(holder);
			} else {
				holder = (ChildHolder) convertView.getTag();
			}
			programNetRes = resGroup.get(groupPosition).getPrograms();
			String content = programNetRes.get(arg1).getName();
			if (content != null && content.equals("more...")
					&& ((arg1 + 1) == programNetRes.size())) {
				holder.directro.setVisibility(View.GONE);
				holder.resProgram.setGravity(Gravity.RIGHT);
				content = getString(R.string.more);
			} else {
				holder.resProgram.setGravity(Gravity.LEFT);
				holder.directro.setVisibility(View.VISIBLE);
				String temp = programNetRes.get(arg1).getJs();
				if (Util.isJs(programNetRes) && temp != null
						&& temp.trim().length() > 0) {
					content = content + "(" + temp + ")";
				}
			}
			holder.resProgram.setText(content);
			return convertView;
		}

		@Override
		public int getChildrenCount(int arg0) {
			if (resGroup.get(arg0) != null
					&& resGroup.get(arg0).getPrograms() != null) {
				return resGroup.get(arg0).getPrograms().size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getGroup(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public int getGroupCount() {
			// TODO Auto-generated method stub
			return resGroup.size();
		}

		@Override
		public long getGroupId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		class GroupHolder {
			ImageView serverLogo;
			TextView serverName;
		}

		@Override
		public View getGroupView(int arg0, boolean arg1, View arg2,
				ViewGroup arg3) {
			GroupHolder holder = new GroupHolder();
			if (arg2 == null) {
				arg2 = View.inflate(context, R.layout.layout_ott_group, null);
				holder.serverLogo = (ImageView) arg2
						.findViewById(R.id.server_ott_logo);
				holder.serverName = (TextView) arg2
						.findViewById(R.id.server_ott);
				arg2.setTag(holder);
			} else {
				holder = (GroupHolder) arg2.getTag();
			}
			holder.serverName.setText(resGroup.get(arg0).getServerName_ch());
			String logoUrl = resGroup.get(arg0).getServerLogoUrl();
			if (logoUrl != null && logoUrl.startsWith("http://")) {
				if (logoCache.containsKey(logoUrl)
						&& logoCache.get(logoUrl).get() != null) {
					Bitmap posterBit = logoCache.get(logoUrl).get();
					holder.serverLogo.setImageBitmap(posterBit);
					holder.serverLogo.setVisibility(View.VISIBLE);
					holder.serverName.setVisibility(View.GONE);
				} else {
					if (logoAsync != null && logoAsync.isCancelled()) {
						logoAsync.cancel(true);
						logoAsync = null;
					} else {
						logoAsync = new LogoAsyncTask();
					}
					logoAsync.execute(logoUrl);

				}
			} else {
				holder.serverName.setVisibility(View.VISIBLE);
				holder.serverLogo.setVisibility(View.GONE);
			}
			return arg2;
		}

		@Override
		public boolean hasStableIds() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			// TODO Auto-generated method stub
			return true;
		}
	}

	public void setTestData() {
		ottList = new ArrayList<OTTInfo>();
		for (int i = 0; i < 3; i++) {
			OTTInfo res = new OTTInfo();
			res.setServerName_ch("友朋" + i);
			ottList.add(res);
		}
		OTTInfo res1 = new OTTInfo();
		res1.setServerName_ch("友朋");
		res1.setMore("http://test.haieross.com/ottlogo/youpeng.png");
		res1.setIs("web");
		res1.setIs("1");
		ArrayList<ThridProgram> progs = new ArrayList<ThridProgram>();
		for (int i = 1; i < 3; i++) {
			ThridProgram prog = new ThridProgram();
			prog.setJs(i + "");
			prog.setName("鹿镇传奇" + i);
			progs.add(prog);
		}
		res1.setPrograms(progs);
		ottList.add(res1);
		// ==========================
		OTTInfo res2 = new OTTInfo();
		res2.setServerName_ch("moretv");
		res2.setMore("http://test.haieross.com/ottlogo/youpeng.png");
		res2.setApkName("com.moretv.tvapp");
		res2.setIs("apk");
		res2.setIs("1");
		progs = new ArrayList<ThridProgram>();

		String[] strs = { "page=detail,sid=o8l7g6cdh6wy",
				"page=detail&sid=9wruv0345hvw", "page=detail&sid=o8bctviks9ce",
				"page=detail&sid=vxb223bdb2u9&ReturnMode=0",
				"page=detail&sid=9we4v0s9l72c&ReturnMode=0",
				"page=detail&sid=9we4v0tvwy9w&ReturnMode=0",
				"page=detail&sid=9we4v0uwa1vx&ReturnMode=0",
				"page=detail&sid=vx6juwnol7p8", "page=detail&sid=vx6j1bklwxtu" };
		for (int i = 0; i < strs.length; i++) {
			ThridProgram prog = new ThridProgram();
			prog.setPid(strs[i]);
			prog.setName(strs[i]);
			progs.add(prog);
		}
		res2.setPrograms(progs);
		ottList.add(res2);
		mhandler.sendEmptyMessage(EPGWeb.DATA_SUC);
	}

	private void getQueryData() {
		Intent intent = getIntent();
		programName = intent.getStringExtra("PRO_NAME");
		programName = programName.replaceAll(" ", "");
		startActivity = intent.getStringExtra("StartActivity");
		programType = intent.getStringExtra("PRO_TYPE");

		js = intent.getStringExtra("PRO_EPISODE");
		if (js == null) {
			js = "0";
		} else if (js.trim().length() < 0) {
			js = "0";
		}
		if (Function.testData.get("TestOtt")) {
			programName = "陆贞传奇";
			programType = "92";
			js = "0";
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
		case KeyEvent.KEYCODE_DPAD_LEFT:
			Intent intent = new Intent();
			if (startActivity.equals("ProgramListActivity")) {
				if (Function.function.get("actorInfor")) {
					intent.setClass(context, ProgramActorActivity.class);
				} else {
					intent.setClass(context, ProgramListActivity.class);
				}
			} else if (startActivity.equals("AcrossChannelSearchActivity")) {
				intent.setClass(context, AcrossChannelSearchActivity.class);
			}
			startActivity(intent);
			break;
		case KeyEvent.KEYCODE_ENTER:
			if (isOutTme) {
				setDataSetup();
			}
			break;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
}
